package com.fpost.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.fpost.constants.ActionConstants;
import com.fpost.domain.ArticleComment;
import com.fpost.form.ArticlePresentationForm;
import com.fpost.form.dto.UserDTO;
import com.fpost.manager.ArticleCommentManager;
import com.fpost.manager.ArticleManager;
import com.fpost.security.ActionSecurityUtils;
import com.fpost.util.CommonUtils;
import com.fpost.util.DateUtil;

public class ArticleCommentAction extends Action {
	
	private static Logger log = Logger.getLogger(ArticleCommentAction.class);
	
	public ActionForward execute(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		
		//set current path in session
		CommonUtils.setCurrentPathInSession(request, mapping);
		
		String forward = ActionConstants.SUCCESS;
		ArticlePresentationForm presentationForm = (ArticlePresentationForm) form;
		String articleIdStr = null;
		try {
			// to make a comment you need to register and sign in
			UserDTO userDTO = ActionSecurityUtils.getUserDTO_fromSession(request);
			if (userDTO == null) {
				forward = ActionConstants.LOGIN;				
			} else {
				articleIdStr = (String) request.getParameter("articleId");
				String comment = presentationForm.getComment();

				if (!"".equals(comment) && comment.length() <= 500) {
					long articleId = Long.parseLong(articleIdStr);					
					long userId = Integer.parseInt(userDTO.getUserId());

					ArticleComment articleComment = new ArticleComment();
					articleComment.setArticle(new ArticleManager().getArticleById(articleId));
					articleComment.setComment(CommonUtils.replaceLineSeparator(comment));
					articleComment.setCreatedOn(DateUtil.getGMTCalendar().getTime());
					articleComment.setCreatedBy(userId);
					articleComment.setCreatedIp(request.getRemoteAddr());

					new ArticleCommentManager().save(articleComment);
					return new ActionForward("articlePresentationAction.do?articleId=" + articleId, true);
				}
			} 
		} catch (NumberFormatException e) {
			log.error(e.getMessage(), e);
			forward = ActionConstants.FAILURE;
		} catch (Exception e) {
			log.error(e.getMessage(), e);
			forward = ActionConstants.SYSTEM_FAILURE;
		}
		
		return mapping.findForward(forward);
	}
}
